﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using CommunitySystem.PageView;
using CommunitySystem.JinShengService;
using EHR.Common;

namespace CommunitySystem
{
    public partial class CandidatorCheckWindow : ChildWindow
    {
        public JinShengService.JinShen_MainInfo _MainInfo = null;

        private JinShengService.JinShen_CompetSpeech_Main SpeechMain = null;

        private JinShengService.JinShen_Democraticevaluation_Main EvaMain = null;

        private PublicOfficialSelectionService.PublicOfficialSelectionServiceClient _uploadClient = null;

        private JinShengService.JinShengServiceClient _Client = null;
        public bool ReturnTrue = false;
        private string _bm = "";
        public CandidatorCheckWindow(JinShengService.JinShen_MainInfo MainInfo, string bm,bool isck)
        {
            InitializeComponent();
            _bm = bm;
          

            if (MainInfo.PromotType.Equals("竞争上岗"))
            {
                this.iskx.Header = "竞争演讲";
                btnSC.Visibility = Visibility.Visible;
            }
            else if (MainInfo.PromotType.Equals("选举"))
            {
                this.iskx.Header = "竞争演讲(可选)";
                btnSC.Visibility = Visibility.Visible;
            }
            else btnSC.Visibility = Visibility.Collapsed;
            if (MainInfo.Status == JinShenConst.STATUS_Candidate_Look) btnSC.Visibility = Visibility.Collapsed;

            _uploadClient = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            _Client = new JinShengService.JinShengServiceClient();
            _uploadClient.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(_uploadClient_UploadFileCompleted);
            _MainInfo = MainInfo;
            if (_MainInfo.Status.Equals(CommunitySystem.PageView.JinShenConst.STATUS_CandidateCheck_Pass))//新增
            {
                if (_MainInfo.PromotType.Equals("竞争上岗") || _MainInfo.PromotType.Equals("选举"))
                    SpeechMain = new JinShengService.JinShen_CompetSpeech_Main() { MainID = _MainInfo.ID, CreateDay = DateTime.Now, CreateUser = EHR.Common.Session.LoginUser.LoginName, Details = new System.Collections.ObjectModel.ObservableCollection<JinShengService.JinShen_CompetSpeech_Detail>() };
                EvaMain = new JinShengService.JinShen_Democraticevaluation_Main() { MainID = _MainInfo.ID, Details = new System.Collections.ObjectModel.ObservableCollection<JinShengService.JinShen_Democraticevaluation_Detail>(), Realcount = 0, TotalCount = 0 };
                foreach (var d in _MainInfo.Details)
                {
                    if (SpeechMain != null)
                    {
                        JinShengService.JinShen_CompetSpeech_Detail detail = new JinShengService.JinShen_CompetSpeech_Detail() { EmpID = d.EmpBasicID, EmpName = d.Name };
                        SpeechMain.Details.Add(detail);
                    }
                    JinShengService.JinShen_Democraticevaluation_Detail detail1 = new JinShengService.JinShen_Democraticevaluation_Detail() { EmpID = d.EmpBasicID, EmpName = d.Name,AgreeCount=0,DisAgreeCount=0,GiveUpCount=0 };

                    EvaMain.Details.Add(detail1);
                }
                DataBinding();
            }
            else//编辑审核
            {
                _Client.GetDemocraEvalutionCompleted += (sender, e) =>
                {
                    EvaMain = e.Result.LastOrDefault();
                    if (_MainInfo.PromotType.Equals("竞争上岗") || _MainInfo.PromotType.Equals("选举"))
                    {
                        _Client.GetCompetSpeechMainAsync("MainID=" + _MainInfo.ID);
                    }
                    else
                    {
                        DataBinding();
                    }
                };

                _Client.GetCompetSpeechMainCompleted += (sender, e) =>
                {
                    SpeechMain = e.Result.LastOrDefault();
                    DataBinding();
                };

                _Client.GetDemocraEvalutionAsync("MainID=" + _MainInfo.ID);
            }

              //保存审核相关记录
            _Client.AddJinShen_SHJLDetailCompleted += (ss, ee) =>
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage(ee.UserState.ToString());
                ReturnTrue = true;
                this.DialogResult = true;
            };
            _Client.SaveDetailCheckCompleted += (sender, e) =>
            {
                if (e.Error == null && e.Result == true)
                {
                     JinShen_SHJLDetail shjl = new JinShen_SHJLDetail();
                     shjl.Name = "竞争上岗及民主测评情况";
                     if (!string.IsNullOrEmpty(shjl.Name))
                         _Client.AddJinShen_SHJLDetailAsync(shjl, MainInfo, "保存成功!");
                    //SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功!");
                    //ReturnTrue = true;
                    //this.DialogResult = true;
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败!");
                    ReturnTrue = false;
                }
            };

            _Client.UpdateJinShenMStatusCompleted += (sender, e) =>
            {
                if (e.Error == null && e.Result > 0)
                {
                    //SilverlightMessageBoxLibrary.Message.InfoMessage("查看成功！");
                    //ReturnTrue = true;
                    //this.DialogResult = true;
                    JinShen_SHJLDetail shjl = new JinShen_SHJLDetail();
                    shjl.Name = "竞争上岗及民主测评情况";
                    shjl.JSMID = MainInfo.MId;
                    shjl.Status = MainInfo.Status;
                    shjl.BLDate = shjl.CreateDate = DateTime.Now;
                    shjl.CreateUser = Session.LoginUser.LoginName;
                    if (!string.IsNullOrEmpty(shjl.Name))
                        _Client.AddJinShen_SHJLDetailAsync(shjl, MainInfo, "查看成功!");
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("查看失败！");
                    ReturnTrue = false;
                }
            };

            if (isck)
            {
                this.OKButton.Visibility = Visibility.Collapsed;
                btnSC.Visibility = Visibility.Collapsed;
            }

        }

        private readonly string fileDictionary = "file";

        void _uploadClient_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            var file = e.UserState as UploadFileInfo;
            if (file.Context.Count > 0)
            {
                _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], false, file);
                file.Context.RemoveAt(0);
            }
            else
            {
                if (files.Values.LastOrDefault() == file)
                {
                    _Client.SaveDetailCheckAsync(EvaMain, SpeechMain, _MainInfo);
                }
            }
        }

        private Dictionary<string, UploadFileInfo> files = new Dictionary<string, UploadFileInfo>();
        private int _maxFileSize = int.MaxValue;

        private FileCollection _files;
        private FileCollection _filesList;
        private int _maxUpload = 4;
        private string _customParams;
        private string _fileFilter;
        private void DataBinding()
        {
            //EvaMain.PropertyChanged += (sender1, e1) =>
            //{
            //    if (e1.PropertyName.Equals("GiveUpCount"))
            //    {
            //        try
            //        {
            //            var detail = sender1 as JinShengService.JinShen_Democraticevaluation_Detail;
            //            int count = (int)detail.AgreeCount + (int)detail.DisAgreeCount + (int)detail.GiveUpCount;
            //            if (count > 0)
            //            {
            //                var rate = (int)detail.DisAgreeCount * 100.0 / count;
            //                detail.UnAgreeRate =  (decimal)Math.Round(rate, 2);
            //            }
            //        }
            //        catch (Exception)
            //        {
            //        }
            //    }
            //};
            if (_MainInfo.PromotType != "竞争上岗"&&_MainInfo.PromotType != "选举")
            {
                LayoutRoot.RowDefinitions[1].Height = new GridLength(0);
                GridSpeech.Height = 0;
                this.Height = 360;
            }
            //else if ()
            //{
            //    LayoutRoot.RowDefinitions[1].Height = new GridLength(0);
            //    GridSpeech.Height = 0;
            //    this.Height = 360;
            //}
            else
            {
                GridSpeech.DataContext = SpeechMain;
                foreach (var d in SpeechMain.Details)
                {
                    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, DataContext = d, Margin = new Thickness(5) };
                    TextBlock tb = new TextBlock() { Text = d.EmpName, Width = 35, Margin = new Thickness(3) };
                    sp.Children.Add(tb);
                    //TextBox tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), MinWidth=120 };
                    //tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("Decription") { Mode = System.Windows.Data.BindingMode.TwoWay });
                    //sp.Children.Add(tbox);
                    _files = new FileCollection(_customParams, _maxUpload);
                    if (!string.IsNullOrEmpty(d.realName))
                    {

                        //_files = new FileCollection(_customParams, _maxUpload);
                        var uf = new UserFile() { FileName = d.GuidName, FileNameG = d.realName, State = Constants.FileStates.Finished, Percentage = Convert.ToInt32(d.Percentage), BytesUploaded = Convert.ToDouble(d.FileSize), FileSize = Convert.ToDouble(d.FileSize) };
                        _files.Add(uf);

                    }
                  

                    UpLoadCon up=new UpLoadCon(_files);
                    HyperlinkButton hlb = new HyperlinkButton() { Content = "上传演讲内容", Margin = new Thickness(5, 0, 0, 0), DataContext = d };
                   
                    HyperlinkButton xz = new HyperlinkButton() { Content = "演讲内容下载", Margin = new Thickness(5, 0, 0, 0), DataContext = d,Visibility=Visibility.Collapsed };

                    xz.Click += new RoutedEventHandler(xz_Click);


                    if (_files != null) if (_files.Count > 0) { hlb.IsEnabled = false; xz.Visibility = Visibility.Visible; }
                    if (_files != null) if (_files.Count == 0 && _MainInfo.PromotType == "选举" && _MainInfo.Status != JinShenConst.STATUS_CandidateCheck_Pass) { hlb.IsEnabled = false; xz.Visibility = Visibility.Collapsed; }
                    hlb.Click += (sender, e) =>
                    {
                        CommunitySystem.JinShengService.JinShen_CompetSpeech_Detail detail = (sender as HyperlinkButton).DataContext as CommunitySystem.JinShengService.JinShen_CompetSpeech_Detail;
                    
                        if (_files != null&&_files.Count!=0)
                        {
                            if (_filesList == null) _filesList = new FileCollection(_customParams, _maxUpload);
                            else
                            {
                                var cc = _filesList.Where(p => p.Eid == _files.First().Eid).ToList();
                                if (cc.Count > 0) _filesList.Remove(cc.First());
                            
                            }
                            _filesList.Add(_files.First());
                            var ccc = _files.Where(p => p.Eid == detail.EmpID).ToList();
                            if (ccc.Count > 0) _files.Remove(ccc.First());
                            //_files.Clear();
                        }

                        var openFile = new OpenFileDialog() { Multiselect = false };
                        if (openFile.ShowDialog() == true)
                        {
                            string GuidName = Guid.NewGuid().ToString("N");
                            detail.GuidName = GuidName;
                            detail.realName = openFile.File.Name;
                        
                            foreach (FileInfo file in openFile.Files)
                            {
                                //string GuidName = Guid.NewGuid().ToString("N");
                                string fileName = file.Name;

                                UserFile userFile = new UserFile();
                                userFile.FileName = GuidName; //GuidName file.Name;
                                userFile.FileNameG = fileName;
                                userFile.IsAdd = true;
                                //userFile.MId =(int) detail.SpeechMainID;
                                userFile.Eid = (int)detail.EmpID;

                                userFile.FileStream = file.OpenRead();

                                if (userFile.FileStream.Length <= _maxFileSize)
                                {
                                    //向文件列表中添加文件信息
                                    //if (_files == null)
                                        _files = new FileCollection(_customParams, _maxUpload);
                                    _files.Add(userFile);
                                    if (_filesList==null) _filesList = new FileCollection(_customParams, _maxUpload);
                                    _filesList.Add(userFile);
                                    detail = new JinShen_CompetSpeech_Detail() { GuidName = userFile.FileName, realName = userFile.FileNameG };
                                    up.FilesList = _files;
                                    up.Files = _files;
                                   
                                }
                                else
                                    SilverlightMessageBoxLibrary.Message.InfoMessage("上传最大文件大小：" + (_maxFileSize / 1024).ToString() + "KB.");
                            }

                          
                         
                        }
                    };
                    sp.Children.Add(hlb);
                    sp.Children.Add(xz);
                 
                    svDetails.Children.Add(sp);

                    svDetails.Children.Add(up);

                }
            }
            GridEvalution.DataContext = EvaMain;
            foreach (var d in EvaMain.Details)
            {
                d.PropertyChanged += (sender1, e1) =>
                {
                    if (e1.PropertyName.Equals("GiveUpCount") || e1.PropertyName.Equals("AgreeCount") || e1.PropertyName.Equals("DisAgreeCount"))
                    {
                        try
                        {
                            var detail = sender1 as JinShengService.JinShen_Democraticevaluation_Detail;
                            int count = (int)detail.AgreeCount + (int)detail.DisAgreeCount + (int)detail.GiveUpCount;
                            if (count > 0)
                            {
                                var rate = (int)detail.DisAgreeCount * 100.0 / count;
                                detail.UnAgreeRate = (decimal)Math.Round(rate, 2);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                };
                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, DataContext = d, Margin = new Thickness(5) };
                TextBlock tb = new TextBlock() { Text = d.EmpName + ":", Width = 35, Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tb = new TextBlock() { Text = "同意", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                TextBox tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width = 30 };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("AgreeCount") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp.Children.Add(tbox);


                tb = new TextBlock() { Text = "票, 不同意", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width = 30 };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("DisAgreeCount") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp.Children.Add(tbox);

                tb = new TextBlock() { Text = "票, 弃权", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width = 30 };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("GiveUpCount") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp.Children.Add(tbox);
                tb = new TextBlock() { Text = "票。", Margin = new Thickness(3) };
                sp.Children.Add(tb);



                tb = new TextBlock() { Text = "  不同意率:", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width = 40, IsReadOnly = true };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("UnAgreeRate") { Mode = System.Windows.Data.BindingMode.TwoWay, StringFormat = "{0:.00}" });
                sp.Children.Add(tbox);
                tb = new TextBlock() { Text = "%", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                svDetails2.Children.Add(sp);
            }
        }
        SaveFileDialog openFile;
        private List<byte> fileContent = new List<byte>();
        void xz_Click(object sender, RoutedEventArgs e)
        {
            CommunitySystem.JinShengService.JinShen_CompetSpeech_Detail detail = (sender as HyperlinkButton).DataContext as CommunitySystem.JinShengService.JinShen_CompetSpeech_Detail;
                       
            SilverlightMessageBoxLibrary.CustomMessage cm = new SilverlightMessageBoxLibrary.CustomMessage("确认要下载此方案吗?", SilverlightMessageBoxLibrary.CustomMessage.MessageType.Confirm, null);
            cm.Show();
            cm.OKButton.Click += (sender1, e1) =>
            {

                string extend = detail.realName.Substring(detail.realName.LastIndexOf('.'));
                // var openFile = new SaveFileDialog() { Filter = string.Format("{0}|*.{0}", extend) };
                openFile = new SaveFileDialog() { Filter = string.Format("{0}|*.{0}", extend) };
                if (openFile.ShowDialog() == true)
                {
                    fileContent.Clear();
               

                    _Client.DownLoadFile1Completed -= new EventHandler<JinShengService.DownLoadFile1CompletedEventArgs>(_Client_DownLoadFile1Completed);
                    _Client.DownLoadFile1Completed += new EventHandler<JinShengService.DownLoadFile1CompletedEventArgs>(_Client_DownLoadFile1Completed);

                    _Client.DownLoadFile1Async(detail.GuidName);
                }

            };
        }

        void _Client_DownLoadFile1Completed(object sender, JinShengService.DownLoadFile1CompletedEventArgs e)
        {
            Stream myStream;
            if ((myStream = openFile.OpenFile()) != null)
            {
                using (BinaryWriter bw = new BinaryWriter(myStream))
                {

                    bw.Write(e.Result);
                    myStream.Dispose();
                    myStream.Close();
                    SilverlightMessageBoxLibrary.Message.InfoMessage("下载完毕!");
                 
                }

            }
        }

    

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(_bm))
            {
                _MainInfo.Status = CommunitySystem.PageView.JinShenConst.STATUS_Candidate_LookTrue;//"一查看";
                _Client.UpdateJinShenMStatusAsync(_MainInfo.ID, CommunitySystem.PageView.JinShenConst.STATUS_Candidate_LookTrue);
            }
            else
            {
                if (Validate())
                {
                    #region 上传文件
                    //_MainInfo.Status = CommunitySystem.PageView.JinShenConst.STATUS_Candidate_Approved;//"候选人审核中";

                    _MainInfo.Status = CommunitySystem.PageView.JinShenConst.STATUS_Candidate_Look;//"部门领导查看";

                    //if (files.Count > 0)//有附件上传
                    //{
                    //    foreach (var key in files.Keys)
                    //    {
                    //        var file = files[key];
                    //        if (file.Context.Count <= 0)
                    //        {
                    //            SilverlightMessageBoxLibrary.Message.ErrorMessage("上传的文件内容不能为空!");
                    //            return;
                    //        }
                    //        _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], true, file);
                    //        file.Context.RemoveAt(0);
                    //    }
                    //}
                    //else//没有附件
                    //{
                    //    _Client.SaveDetailCheckAsync(EvaMain, SpeechMain, _MainInfo);
                    //}
                    if (_filesList != null && _filesList.Count != 0)
                    {
                    
                        if (_filesList.Where(p => p.State == Constants.FileStates.Pending).Count() > 0)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage("您所选的附件还未上传，请点击上传按钮进行上传！");
                            return;
                        }
                        if (_filesList.Where(p => p.State == Constants.FileStates.Uploading).Count() > 0)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage("附件正在上传，请稍后！");
                            return;
                        }
                        else
                        {
                     
                                foreach (var item1 in _filesList)
                                {
                                    var dd = SpeechMain.Details.Where(c => c.GuidName == item1.FileName).ToList();
                                    if (dd.Count > 0)
                                    {
                                        var cc = dd.First();
                                        cc.Status = (item1.State).ToString();
                                        cc.Percentage = item1.Percentage.ToString();
                                        cc.FileSize = item1.FileSize.ToString();
                                    }
                                }

                                foreach (var item11 in SpeechMain.Details.Where(p => p.Status == "Error").ToList())
                                {
                                    SilverlightMessageBoxLibrary.Message.ErrorMessage(item11.EmpName+"文件上传失败，请重新选择文件上传！");
                                    return;
                                }
                        }
                    }
                    _Client.SaveDetailCheckAsync(EvaMain, SpeechMain, _MainInfo);

                    #endregion
                }
            }

        }



        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        private bool Validate()
        {
            #region 竞争上岗
            if (SpeechMain != null && _MainInfo.PromotType.Equals("竞争上岗"))
            {
                var detail = SpeechMain.Details.Where(c => string.IsNullOrEmpty(c.GuidName)).FirstOrDefault();
                if (detail != null)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传" + detail.EmpName + "的演讲附件!");
                    return false;
                }
                //if (string.IsNullOrEmpty(SpeechMain.Description))
                //{
                //    //SilverlightMessageBoxLibrary.Message.ErrorMessage("请填写描述信息!");
                //    //return false;
                //}
            }
            #endregion

            #region 民主测评
            if (EvaMain.TotalCount <= 0 || EvaMain.TotalCount == null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("应参加评测人数填写错误!");
                return false;
            }
            if (EvaMain.Realcount <= 0 || EvaMain.Realcount == null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("实到人数填写错误!");
                return false;
            }
            if (EvaMain.Realcount > EvaMain.TotalCount)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("实到人数不能大于应参加人数!");
                return false;
            }

            if (EvaMain.Realcount > EvaMain.TotalCount)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("实到人数不能大于应参加人数!");
                return false;
            }
            var de = EvaMain.Details.Where(c => c.AgreeCount < 0 || c.AgreeCount == null).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的同意票数不能小于0");
                return false;
            }

            de = EvaMain.Details.Where(c => c.DisAgreeCount < 0 || c.DisAgreeCount == null).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的不同意票数不能小于0");
                return false;
            }

            de = EvaMain.Details.Where(c => c.GiveUpCount < 0 || c.GiveUpCount == null).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的弃权票数不能小于0");
                return false;
            }

            de = EvaMain.Details.Where(c => c.GiveUpCount + c.DisAgreeCount + c.AgreeCount > EvaMain.Realcount).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的票数不能大于实到人数");
                return false;
            }

            #endregion
            return true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void btnSC_Click(object sender, RoutedEventArgs e)
        {
            if (_filesList==null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择上传的附件！");
                return;
            }
            if (_filesList.Count == 0)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请选择上传的附件！");
                return;
            }
            else
            {
                if (_files.Count != 0) _filesList.Add(_files.First());
                _filesList.UploadFiles();

            }
        }
    }
}

